var _api = require("../../api.js"),
  app = getApp();
var time_util = require('../../utils/util.js');
const {
  $Toast
} = require('../../components/iview/base/index');
import Notify from '../../components/vant/notify/notify';
Page({
  data: {
    imgUrls: [
      '../../images/top_home_0.jpg',
      '../../images/top_home_1.jpg'
    ],
    indicatorDots: false, //是否显示面板指示点
    autoplay: true, //是否自动播放
    interval: 3000, //停留时间间隔
    duration: 1000, //播放时长
    previousMargin: '50px', //前边距，可用于露出前一项的一小部分，接受 px 和 rpx 值
    nextMargin: '50px', //后边距，可用于露出后一项的一小部分，接受 px 和 rpx 值
    circular: false, //是否采用衔接滑动
    currentSwiperIndex: 0, //swiper当前索引
    /** 初始项目id */
    parent_id: 0,
    xf_avatar: '../../images/myyuyue.png',
    /** 未授权 */
    authorize: false,
    loading: false,
    disabled: true,
    show_time: false,
    time: '',
    minDate: new Date().getTime(),
    formatter(type, value) {
      if (type === 'year') {
        return `${value} 年`;
      } else if (type === 'month') {
        return `${value} 月`;
      } else if (type === 'day') {
        return `${value} 日`;
      } else if (type === 'hour') {
        return `${value} 时`;
      } else if (type === 'minute') {
        return `${value} 分`;
      }
      return value;
    },
    projects: [],
    areas: [],

    /** 用户 open_id */
    open_id: '',
    /** 服务项目 */
    project: '',
    /** 内容 */
    area: '',
    /** 联系人 */
    name: '',
    /** 手机号 */
    phone: '',
    /** 地址 */
    address: '',
    /** 地址 */
    price: 0,
  },
  swiperBindchange(e) {
    this.setData({
      currentSwiperIndex: e.detail.current
    })
  },
  /**  生命周期函数--监听页面加载 */
  onLoad: function (options) {
    var that = this;
    //查看是否授权
    wx.getSetting({
      success: function (res) {
        /** 用户已授权 */
        if (res.authSetting['scope.userInfo']) {
          console.log('open_id -- > ' + app.get_open_id())
          that.setData({
            open_id: app.get_open_id(),
            authorize: true,
            disabled: false
          })
        }
      }
    });
  },
  /** 生命周期函数--监听页面显示 */
  onShow: function () {
    /** 获取服务项目信息 */
    let that = this;
    wx.request({
      url: _api.get_serv_projects,
      success: function (res) {
        that.setData({
          projects: res.data.data
        });
      }
    })
  },
  /**  展示服务项目选项 */
  show_picker(e) {
    let that = this;
    let item = e.currentTarget.dataset.pickername;
    if (item != 'show_area') {
      this.setData({
        [item]: true
      });
    }
    /** 获取项目内容 */
    if (item == 'show_area') {
      if (that.data.parent_id != 0) {
        wx.request({
          url: _api.get_serv_projects,
          data: {
            parent_id: that.data.parent_id
          },
          success: function (res) {
            console.log(res)
            that.setData({
              areas: res.data.data,
              [item]: true
            });
          }
        })
      } else {
        $Toast({
          content: '请先选择服务项目',
          type: 'warning'
        });
      }
    }
  },
  /** picker 改变事件 */
  on_input(event) {
    let item = event.currentTarget.dataset.inputname;
    if (item === 'time') {
      this.setData({
        [item]: time_util.formatTimeTwo(event.detail, 'Y-M-D h:m')
      });
    } else {
      this.setData({
        [item]: event.detail.value.text,
      });
      if (item === 'project') {
        /** 设置父类 id */
        this.setData({
          parent_id: event.detail.value.id
        });
      }else{
        /** 设置价格 */
        this.setData({
          price: event.detail.value.price
        });
      }
    }
  },
  /** 选择确认 */
  confirm(e) {
    this.on_input(e);
    let item = e.currentTarget.dataset.pickername;
    this.setData({
      [item]: false
    });
  },
  /** 取消 */
  cancel(e) {
    let item = e.currentTarget.dataset.pickername;
    this.setData({
      [item]: false
    });
  },

  /******************  授权页面 ******************/

  /** 用户没有授权 跳转到授权页面 */
  to_login() {
    wx.navigateTo({
      url: '../login/login',
    })
  },

  /******************  我的预约 ******************/

  my_appoint() {
    wx.navigateTo({
      url: '../my_appoint/my_appoint',
    })
  },

  /** 选择地图 */
  select_address() {
    var that = this
    wx.getSetting({
      success(res) {
        console.log('res是否开启位置授权', res)
        if (!res.authSetting['scope.userLocation']) {
          wx.authorize({
            scope: 'scope.userLocation',
            success() {
              wx.chooseLocation({
                success: res => {
                  console.log('打开地图选择位置确定', res)
                  var addr = res.address
                  that.setData({
                    address: addr
                  })
                },
                fail: res => {
                  console.log('打开地图选择位置取消', res)
                }
              })
            },
            fail() {
              app.fetchAgainLocation()
            }
          })
        } else {
          // 已经授权了就会直接进入地图
          wx.chooseLocation({
            success: res => {
              console.log('打开地图选择位置确定', res)
              var addr = res.address
              that.setData({
                address: addr
              })
            },
            fail: res => {
              console.log('打开地图选择位置取消', res)
            }
          })
        }
      }
    })
  },

  /******************  提交预约 ******************/

  /** 输入框的值传输 */
  bind_key_input: function (e) {
    let item = e.currentTarget.dataset.model;
    console.log(item)
    this.setData({
      [item]: e.detail
    });
  },

  /** 预约提交 */
  sub_appoint() {
    console.log(this.data.open_id)
    let that = this;
    if (this.data.project != '' && this.data.area != '' && this.data.name != '' && this.data.phone != '' && this.data.address != '') {
      if (!/^1[34578]\d{9}$/.test(this.data.phone)) {
        Notify({
          background: '#f8ac59',
          message: '手机号码格式不正确'
        });
        return false;
      }

      this.setData({
        loading: true,
        disabled: true
      })
      /** 提交预约接口请求 */
      var t = new Object();
      /** 传输的参数 */
      t = {
        openId: this.data.open_id,
        project: this.data.project,
        area: this.data.area,
        name: this.data.name,
        phone: this.data.phone,
        address: this.data.address,
        time: this.data.time,
        price: this.data.price,
        remark: ''
      }
      /** 0 元 */
      if (this.data.price === 0) {
        wx.request({
          url: _api.appoint.add_appoint,
          data: t,
          method: "POST",
          header: {
            "content-type": "application/x-www-form-urlencoded"
          },
          responseType: 'text',
          success: function (res) {
            setTimeout(() => {
              that.setData({
                loading: false,
                disabled: false
              })
              /** 跳转到预约详情页 */
              wx.navigateTo({
                url: '../appoint_success/appoint_success?appiont_no=' + res.data.data,
              })
            }, 2000)
          }
        })
      } else {
        /** 非 0 元 购买 */
        wx.request({
          url: _api.appoint.to_buy,
          data: t,
          method: "POST",
          header: {"content-type": "application/x-www-form-urlencoded"},
          success: function (r) {
            console.log(r);
            if (r.data.code == 200) {
              var data = r.data.data;
              wx.requestPayment({
                timeStamp: data.timeStamp.toString(),
                nonceStr: data.nonceStr,
                package: data.package,
                signType: "MD5",
                paySign: data.paySign,
                success: function () {
                  console.log("支付成功");
                },
                fail: function () {
                  console.log("支付失败");
                  return;
                },
                complete: function (res) {
                  console.log("支付完成");
                  if (res.errMsg == "requestPayment:ok") {
                    // wx.showToast({
                    //   title: "支付成功",
                    //   icon: "success"
                    // });
                    setTimeout(() => {
                      that.setData({
                        loading: false,
                        disabled: false
                      })
                      /** 跳转到预约详情页 */
                      wx.navigateTo({
                        url: '../appoint_success/appoint_success?appiont_no=' + data.appoint_no,
                      })
                    }, 1500)
                  }
                  return;
                }
              });
            } else {
              wx.showToast({
                title: "预约失败",
              });
            }
          }
        });
      }
    } else {
      $Toast({
        content: '数据未填写完整',
        type: 'warning'
      });
      return false;
    }


  }
})